package com.onlinestudy.service;

import com.onlinestudy.domain.KnowledgeBase;
import com.onlinestudy.domain.KnowledgeBaseDocument;
import com.onlinestudy.repository.KnowledgeBaseRepository;
import com.onlinestudy.repository.KnowledgeBaseDocumentRepository;
import com.onlinestudy.repository.CourseRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

public interface KnowledgeBaseService {
    KnowledgeBase createKnowledgeBase(Long courseId, String name);
    KnowledgeBaseDocument uploadDocument(Long knowledgeBaseId, MultipartFile file);
    Optional<KnowledgeBase> getKnowledgeBaseByCourse(Long courseId);
    List<KnowledgeBaseDocument> getDocuments(Long knowledgeBaseId);
    Map<String, Object> generateOutline(Long knowledgeBaseId);
    Map<String, Object> generatePPT(Long knowledgeBaseId);
    Map<String, Object> generateExam(Long knowledgeBaseId);
    Map<String, Object> autoGrade(Map<String, Object> request);
}

@Service
class KnowledgeBaseServiceImpl implements KnowledgeBaseService {

    private final KnowledgeBaseRepository knowledgeBaseRepository;
    private final KnowledgeBaseDocumentRepository documentRepository;
    private final CourseRepository courseRepository;

    public KnowledgeBaseServiceImpl(KnowledgeBaseRepository knowledgeBaseRepository,
                                   KnowledgeBaseDocumentRepository documentRepository,
                                   CourseRepository courseRepository) {
        this.knowledgeBaseRepository = knowledgeBaseRepository;
        this.documentRepository = documentRepository;
        this.courseRepository = courseRepository;
    }

    @Transactional
    @Override
    public KnowledgeBase createKnowledgeBase(Long courseId, String name) {
        return courseRepository.findById(courseId)
                .map(course -> {
                    KnowledgeBase kb = new KnowledgeBase();
                    kb.setCourse(course);
                    kb.setName(name);
                    return knowledgeBaseRepository.save(kb);
                })
                .orElseThrow(() -> new IllegalArgumentException("Course not found"));
    }

    @Override
    public KnowledgeBaseDocument uploadDocument(Long knowledgeBaseId, MultipartFile file) {
        return knowledgeBaseRepository.findById(knowledgeBaseId)
                .map(kb -> {
                    try {
                        // 创建上传目录
                        String uploadDir = "uploads/knowledge-base/" + knowledgeBaseId;
                        Path uploadPath = Paths.get(uploadDir);
                        if (!Files.exists(uploadPath)) {
                            Files.createDirectories(uploadPath);
                        }

                        // 保存文件
                        String fileName = file.getOriginalFilename();
                        Path filePath = uploadPath.resolve(fileName);
                        Files.copy(file.getInputStream(), filePath);

                        // 保存文档记录
                        KnowledgeBaseDocument doc = new KnowledgeBaseDocument();
                        doc.setKnowledgeBase(kb);
                        doc.setFileName(fileName);
                        doc.setFilePath(filePath.toString());
                        doc.setStatus(KnowledgeBaseDocument.Status.READY);

                        return documentRepository.save(doc);
                    } catch (IOException e) {
                        throw new RuntimeException("Failed to upload file", e);
                    }
                })
                .orElseThrow(() -> new IllegalArgumentException("Knowledge base not found"));
    }

    @Override
    public Optional<KnowledgeBase> getKnowledgeBaseByCourse(Long courseId) {
        return knowledgeBaseRepository.findByCourse_Id(courseId);
    }

    @Override
    public List<KnowledgeBaseDocument> getDocuments(Long knowledgeBaseId) {
        return documentRepository.findByKnowledgeBase_Id(knowledgeBaseId);
    }

    @Override
    public Map<String, Object> generateOutline(Long knowledgeBaseId) {
        // TODO: 调用AI服务生成大纲
        Map<String, Object> outline = new HashMap<>();
        outline.put("title", "课程大纲");
        outline.put("chapters", Arrays.asList(
            "第一章：基础知识",
            "第二章：核心概念", 
            "第三章：实践应用"
        ));
        outline.put("generatedAt", new Date());
        return outline;
    }

    @Override
    public Map<String, Object> generatePPT(Long knowledgeBaseId) {
        // TODO: 调用AI服务生成PPT
        Map<String, Object> ppt = new HashMap<>();
        ppt.put("title", "授课PPT");
        ppt.put("slides", Arrays.asList(
            "第1页：课程介绍",
            "第2页：学习目标",
            "第3页：主要内容",
            "第4页：总结"
        ));
        ppt.put("generatedAt", new Date());
        return ppt;
    }

    @Override
    public Map<String, Object> generateExam(Long knowledgeBaseId) {
        // TODO: 调用AI服务生成试卷
        Map<String, Object> exam = new HashMap<>();
        exam.put("title", "课程考试");
        exam.put("questions", Arrays.asList(
            Map.of("type", "multiple_choice", "question", "什么是核心概念？", "options", Arrays.asList("A", "B", "C", "D")),
            Map.of("type", "true_false", "question", "这个说法是否正确？", "options", Arrays.asList("正确", "错误")),
            Map.of("type", "short_answer", "question", "请简述主要观点", "options", new ArrayList<>())
        ));
        exam.put("generatedAt", new Date());
        return exam;
    }

    @Override
    public Map<String, Object> autoGrade(Map<String, Object> request) {
        // TODO: 调用AI服务自动评分
        Map<String, Object> result = new HashMap<>();
        result.put("totalScore", 85);
        result.put("feedback", "整体表现良好，建议加强实践部分");
        result.put("gradedAt", new Date());
        return result;
    }
} 